<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-11-28 14:14
 *
 * Version: 2.0
 */

namespace App\Modules\RedBag\Services;


use App\Exceptions\DbException;
use App\Modules\Employee\Repositories\EmployeeRepository;
use App\Modules\Member\Repositoryies\MemberRepository;
use App\Modules\RedBag\Repositories\RedBagListRepository;
use App\Modules\RedBag\Repositories\RedBagRepository;
use App\Modules\Store\Repositories\StoreRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RedBagService extends BaseService
{
	protected $employeeRepository;
	protected $redBagRepository;
	protected $redBagListRepository;
	protected $memberRepository;
	protected $storeRepository;
	public function __construct(EmployeeRepository $employeeRepository,RedBagRepository $redBagRepository,RedBagListRepository $redBagListRepository,MemberRepository $memberRepository,StoreRepository $storeRepository)
	{
		$this->employeeRepository = $employeeRepository;
		$this->redBagRepository = $redBagRepository;
		$this->redBagListRepository = $redBagListRepository;
		$this->memberRepository = $memberRepository;
		$this->storeRepository = $storeRepository;
	}

	/**
	 * 发红包
	 * @param $params
	 * @param $userId
	 * @return array
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function sendRedBagToMember($params,$userId){
		$userInfo = $this->employeeRepository->isExited($userId);
		$luckyCoin = $params['money'] * $params['create_num'];
		if($luckyCoin > $userInfo->coin){
			return ['status'=>0 ,'msg'=>'抱歉，您的县令币余额不足，请您充值后，继续操作！'];
		}
		$userInfo->coin -= round($params['money'] * $params['create_num'],2);
		$userInfo->save();
		$redBagId = $this->redBagRepository->addItem($params,$userId);
		return ['status'=>1,'msg'=>'红包发送成功！','data'=>$redBagId];
	}


	/**
	 * 回收红包
	 * @param $id
	 * @return array
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function backRedBag($userId,$storeId){
		$redBagInfoList = $this->redBagRepository->getRedBagList($userId,$storeId);
		$storeInfo = $this->storeRepository->isExited($storeId);
		if($redBagInfoList->isEmpty()){
			return ['status'=>1,'msg'=>'红包发完，没有剩余！'];
		}
		$userInfo = $this->employeeRepository->isExited($userId);
		$totalCoin = 0;
		foreach ($redBagInfoList as $redBagInfo){
			$surplusNum =  $redBagInfo->create_num - $redBagInfo->send_num;
			if($surplusNum){
				$totalCoin += $totalCoin;
				$redBagInfo->back_num = $surplusNum;
				$surplusCoin = $redBagInfo->money * $surplusNum;
				$userInfo->coin += $surplusCoin;
				$userInfo->save();
			}
			$redBagInfo->status = 2;
			$redBagInfo->back_at = date('Y-m-d H:i:s');
			$redBagInfo->save();
		}
		Log::info('剩余红包回收的数量为：'.$surplusNum.'，回收的县令币个数为：'.$surplusCoin);
		return  ['status'=>1,'msg'=>'剩余的红包回收完毕！'];
	}


	/**
	 * 抢红包
	 * @param $id
	 * @param $memberId
	 * @param $source
	 * @return array
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function pickUpRedBag($id,$memberId,$source){
		$redBagInfo = $this->redBagRepository->isExited($id);
		$otherRedBagList = $this->redBagListRepository->getMemberListByRedBagId($id);
//		dd($otherRedBagList);
		$selfRedBagList = $this->redBagListRepository->getMemberListSelfByRedBagIdAndUserId($redBagInfo->user_id,$memberId,$redBagInfo->live_id);
//		dd($selfRedBagList,$otherRedBagList);
		$isPickUp = $this->redBagListRepository->findByField(['coupon_id'=>$id,'member_id'=>$memberId])->toArray();
		if(!empty($isPickUp)){
			return ['status'=>0,'msg'=>'对不起，每人只能抢一次，您已经抢过了！','data'=>[ 'pick_up_red_bag'=>[],'other_list'=>$otherRedBagList,'self_list'=>$selfRedBagList]];
		}
		$surplusNum =  $redBagInfo->create_num - $redBagInfo->send_num - $redBagInfo->back_num;
		$memberInfo = $this->memberRepository->isExisted($memberId);
		if(!$surplusNum){
			return ['status'=>0,'msg'=>'红包已被抢完！','data'=>['pick_up_red_bag'=>[],'other_list'=>$otherRedBagList,'self_list'=>$selfRedBagList]];
		}
		DB::beginTransaction();
		try{
			$itemId = $this->redBagListRepository->addItem($redBagInfo,$memberId,$source,$redBagInfo->live_id);
			if($itemId){
				$redBagInfo->send_num += 1;
				$redBagInfo->save();
				$memberInfo->coin += $redBagInfo->money;
				$memberInfo->save();
			}
			$selfRedBagList = $this->redBagListRepository->getMemberListSelfByRedBagIdAndUserId($redBagInfo->user_id,$memberId,$redBagInfo->live_id);
			$otherRedBagList = $this->redBagListRepository->getMemberListByRedBagId($id);
			DB::commit();
			return ['status'=>1,'msg'=>'抢到成功！','data'=>[ 'pick_up_red_bag'=>[
				'id' => $redBagInfo->id,
				'money' => $redBagInfo->money,
				'create_num' => $redBagInfo->create_num,
				'send_num' =>$redBagInfo->send_num,
				'created_at' => $redBagInfo->created_at->format('Y-m-d H:i:s')
			],'other_list'=>$otherRedBagList,'self_list'=>$selfRedBagList]];
		}catch (DbException $dbException){
			DB::rollBack();
			Log::error('抢红包异常：'.$dbException->getMessage());
			return ['status'=>0,'msg'=>'服务器累了，请小主稍后访问'];
		}
	}


	public function lst($redBagId,$liveId){
		$list = $this->redBagListRepository->getListByRedBagId($redBagId,$liveId);
		return ['status'=>1,'msg'=>'获取成功','data'=>$list];
	}

	/**
	 * 检测是否发红包
	 * @param $userId
	 * @param $storeId
	 * @return array
	 */
	public function checkHasRedBag($userId,$storeId,$memberId){
		$redBagInfo = $this->redBagRepository->checkHasRedBag($userId,$storeId);
		$remainNum=0;
		if(!empty($redBagInfo)){
			$remainNum = $redBagInfo->create_num - $redBagInfo->send_num - $redBagInfo->back_num;
			$isPickUp = $this->redBagListRepository->findByField(['coupon_id'=>$redBagInfo->id,'member_id'=>$memberId])->toArray();

		}
		if(empty($redBagInfo)){
			$result = ['status'=>0,'msg'=>"没有发红包！",'data'=>[] ];
		}else if(!empty($isPickUp)){
			$result = ['status'=>0,'msg'=>"您已经抢过红包了",'data'=>[] ];
		}else if(empty($remainNum)){
			$result = ['status'=>0,'msg'=>"红包被抢完了",'data'=>[] ];
		}else{
			$result = ['status'=>1,'msg'=>"发红包了！",'data'=>$redBagInfo];
		}
		return $result;
	}

}